<template>
	<view class="post_file_articles">
		<nav-bar :titleCenter='fales'>分享脑洞
			<view class="sub_btn" slot="right" @click="postAndUpload">发布</view>
		</nav-bar>

		<view class="content">
			<view class="textarea">
				<textarea wrap="hard" v-model="message" maxlength="300" :show-confirm-bar="false" focus="true" :auto-height="true"
				 placeholder="我的快乐源泉" />
				</view>
			<view class="filearea">
				<view class="file_item" v-for="(item, index) in wiatUpFileArry" :key="index">
					<!-- 图片的展示 -->
					<image @click="perViewFile(index)" :src="item.file_type === 0 ? item.file_path : item.previewImage" mode="aspectFill"></image>
					<text @click="removeFile(index)" class="iconfont icon-guanbi file_claer"></text>
					<text @click="perViewFile(index)" v-if="item.file_type === 1" class="iconfont icon-b- video-bofang"></text>
					<text v-if="item.file_type === 1" class="video_preview_info">{{ secondToDate(item.duration) }}</text>
				</view>
			</view>
		</view>

		<view class="bottom_flxed" :style="{ bottom: keyBoard.height + 'px', height: keyBoard.status ? '70rpx' : '150rpx' }">
			<view class="bottom_item" v-on:click="selectImage()">
				<!-- <view class="iconfont icon-zhaoxiangji bottom_item_icon"></view> -->
				<view :class="!keyBoard.status ? 'iconfont icon-zhaoxiangji bottom_item_icon' : 'iconfont icon-zhaoxiangji bottom_item_icon2'"></view>
				<view v-if="!keyBoard.status" class="bottom_item_text">相册</view>
			</view>
			<view class="bottom_item" v-on:click="selectVideos()">
				<!-- <view class="iconfont icon-shipin bottom_item_icon"></view> -->
				<view :class="!keyBoard.status ? 'iconfont icon-shipin bottom_item_icon' : 'iconfont icon-shipin bottom_item_icon2'"></view>
				<view v-if="!keyBoard.status" class="bottom_item_text">小视频</view>
			</view>
			<view class="bottom_item">
				<!-- <view class="iconfont icon-maikefeng-xue bottom_item_icon"></view> -->
				<view :class="!keyBoard.status ? 'iconfont icon-maikefeng-xue bottom_item_icon' : 'iconfont icon-maikefeng-xue bottom_item_icon2'"></view>
				<view v-if="!keyBoard.status" class="bottom_item_text">音频</view>
			</view>
			<view class="bottom_item">
				<view :class="!keyBoard.status ? 'iconfont icon-link bottom_item_icon' : 'iconfont icon-link bottom_item_icon2'"></view>
				<view v-if="!keyBoard.status" class="bottom_item_text">链接</view>
			</view>
		</view>
	</view>
</template>

<script>
import {config} from "../../utils/request/config.js"
import navBar from '../../components/zhouWei-navBar/index.vue';
// let qiniu = require('../../utils/qiniuyun/qiniuUploader.min');
let qiniu = require('../../utils/qiniuyun/qiniuUploader');
let sparkmd5 = require('../../utils/SparkMD5');
const FILE_TYPE = {
	image: 0,
	video: 1,
	audio: 2
};
const FILE_MAX_SIEZ = {
	image: 1024 * 1024 * 4,
	video: 1024 * 1024 * 8,
	audio: 1024 * 1024 * 4
};
export default {
	components: {
		// previewImageAndVideo
		navBar
	},
	data() {
		return {
			wiatUpFileArry: [],
			keyBoard: {
				status: false,
				height: 0
			},
			message: ''
			// videoContext:null
		};
	},
	onReady() {
		uni.onKeyboardHeightChange(res => {
			if (!res.inputId) {
				if (res.height === 0) {
					this.keyBoard.status = false;
				} else {
					this.keyBoard.status = true;
				}
				this.keyBoard.height = res.height;
			}
		});
	},
	methods: {
		secondToDate(second) {
			let h = Math.floor(second / 3600) * 60;
			let m = Math.floor((second / 60) % 60) + h;
			let s = Math.floor(second % 60);
			return m + h + ':' + s;
		},
		resetBottomStatus() {
			this.keyBoard.height = 0;
			this.keyBoard.status = false;
		},
		removeFile(index) {
			this.wiatUpFileArry.splice(index, 1);
		},
		selectImage() {
			if (this.wiatUpFileArry.length < 9) {
				this.resetBottomStatus(); // 恢复大图标
				uni.chooseImage({
					count: 9 - this.wiatUpFileArry.length, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: res => {
						console.log(res);
						res.tempFiles.forEach((item, index) => {
							if (item.size <= FILE_MAX_SIEZ.image) {
								// 获取图片原始信息
								uni.getImageInfo({
									src: item.path,
									success: imgInfoRes => {
										this.wiatUpFileArry.push({
											file_path: imgInfoRes.path,
											file_type: FILE_TYPE.image,
											type_name: imgInfoRes.type,
											file_width: imgInfoRes.width,
											file_height: imgInfoRes.height,
											file_ratio: imgInfoRes.width / imgInfoRes.height,
											size: item.size
										});
									}
								});
							} else {
								uni.showToast({
									title: '第' + index + '个图片超过4MB',
									icon: 'none'
								});
							}
						});
					}
				});
			} else {
				uni.showToast({
					title: '最多选择9个文件哦!',
					icon: 'none'
				});
			}
		},
		selectVideos() {
			if (this.wiatUpFileArry.length < 9) {
				this.resetBottomStatus();
				uni.chooseVideo({
					count: 9 - this.wiatUpFileArry.length,
					// compressed:false,
					maxDuration: 60,
					sourceType: ['camera', 'album'],
					success: res => {
						console.log(res);
						if (res.size <= FILE_MAX_SIEZ.video) {
							this.wiatUpFileArry.push({
								file_path: res.tempFilePath,
								file_type: FILE_TYPE.video,
								previewImage: res.thumbTempFilePath,
								duration: res.duration,
								file_width: res.width,
								file_height: res.height,
								file_ratio: res.width / res.height,
								size: res.size
							});
						} else {
							uni.showToast({
								title: '当前视频超过8MB',
								icon: 'none'
							});
						}
					}
				});
			} else {
				uni.showToast({
					title: '最多选择9个文件哦!',
					icon: 'none'
				});
			}
		},
		perViewFile(toindex) {
			uni.navigateTo({
				url: '../utils/previewImageAndVideo?index=' + toindex,
				success: res => {
					console.log(toindex);
					uni.setStorageSync('previewFileArry', this.wiatUpFileArry);
					uni.setStorageSync('previewFileindex', toindex);
					getApp().globalData.previewFileArry = this.wiatUpFileArry;
				}
			});
		},
		backPage() {
			uni.navigateBack({
				delta: 1
			});
		},
		postAndUpload() {
			// 判断是否符合条件
			let postInfoArrys = {
				content: this.message,
				files: []
			};
			if (this.message.length < 5 || this.message.length > 500) {
				uni.showToast({
					title: '5~500字符哦!',
					icon: 'none'
				});
				return;
			}

			// 验证完毕 弹出上传提示
			uni.showLoading({
				title: '上传中...'
				// mask:true
			});

			// 判断是否有图片 没有图片就上传文字内容
			if (this.wiatUpFileArry.length === 0) {
				this.postarticle(postInfoArrys);
				return;
			}

			/* 循环上传文件！调用七牛返回值样例
				hash: "Ft0M_39uI7XXu1jR8yOvTZoyoy2-"
				imageUrl: "http://q0zr7m3w7.bkt.clouddn.com/9193c718845d4b0e83deed1875d8a925"
				key: "9193c718845d4b0e83deed1875d8a925"
			*/
			let upIndex = 0;
			this.wiatUpFileArry.forEach((item, index) => {
				qiniu.upload(
					item.file_path,
					upload_res => {
						upIndex++;
						if (item.file_type === 0) {
							// 图片上传
							postInfoArrys.files.push({
								file_qiniu_hash: upload_res.hash, // 七牛Hash
								file_path: upload_res.imageUrl, // 文件的网络路径
								file_key: upload_res.key, // 文件的MD5值
								file_type: FILE_TYPE.image, // 文件类型
								file_width: item.file_width,
								file_height: item.file_height,
								file_ratio: item.file_ratio,
								file_preview: '', // 缩略图
								file_type_details: this.getFileTypeDetails(item.file_path) // 文件的类型名 png...
							});
						} else if (item.file_type === 1) {
							// 视频上传
							postInfoArrys.files.push({
								file_qiniu_hash: upload_res.hash, // 七牛Hash
								file_path: upload_res.imageUrl, // 文件的网络路径
								file_key: upload_res.key, // 文件的MD5值
								file_type: FILE_TYPE.video, // 文件类型
								file_width: item.file_width,
								file_height: item.file_height,
								file_ratio: item.file_ratio,
								file_preview: upload_res.imageUrl + '?vframe/jpg/offset/1', // 缩略图
								file_type_details: this.getFileTypeDetails(item.file_path) // 文件的类型名 mp4...
							});
						}
						if (upIndex === this.wiatUpFileArry.length) {
							console.log(postInfoArrys);
							this.postarticle(postInfoArrys);
						} else {
							uni.showLoading({
								title: '上传进度：' + upIndex + '/' + this.wiatUpFileArry.length
								// mask:true
							});
						}
					},
					error => {
						uni.hideLoading();
						uni.showToast({
							title: '发生错误，请重试',
							icon: 'none'
						});
					},
					{
						region: 'SCN',
						uploadURL: 'https://up-z2.qiniup.com',
						domain: 'https://file.ndmrak.com/',
						key: this.make_md5(item.file_path),
						uptokenURL: config.baseURL + '/api/filemanage/upload/'
					}
				);
			});
		},
		make_md5(file) {
			let fileObj = uni.getFileSystemManager().readFileSync(file);
			let spark = new sparkmd5.ArrayBuffer();
			spark.append(fileObj);
			let hexHash = spark.end(false);
			return hexHash;
		},
		getFileTypeDetails(fileName) {
			let nameSplit = fileName.split('.');
			let name = nameSplit[nameSplit.length - 1];
			return name;
		},
		postarticle(postInfoArrys) {
			this.$http
				.request({
					url: '/api/article/ivarticle/',
					data: postInfoArrys,
					method: 'post'
				})
				.then(res => {
					uni.hideLoading();
					if (res.statusCode == 201) {
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						// 清理资源
						this.wiatUpFileArry = [];
						this.message = '';
						// 回到上一页
						this.backPage();
					} else {
						uni.showToast({
							title: '发布失败:' + res,
							icon: 'none'
						});
					}
				})
				.catch(error => {
					uni.hideLoading();
					uni.showToast({
						title: '发生错误：' + error,
						icon: 'none'
					});
					console.log('发生错误：', error);
				});
		}
	}
};
</script>

<style lang="scss">
page {
	height: 100%;
}
.post_file_articles {
	width: 100%;
	height: 100%;
	flex-wrap: wrap;
	overflow: hidden;
	display: block;
}
.iconset {
	margin-left: 15rpx;
	vertical-align: middle;
	font-size: 50rpx;
	height: 70rpx;
	line-height: 70rpx;
}
.top {
	width: 100%;
	height: 85rpx;
	flex-shrink: 0;
	justify-content: space-between;
	align-items: center;
	box-shadow: 1px 1px 1px #c0c0c0;
	.previous_page {
		width: 70rpx;
		height: 70rpx;
		text-align: center;
	}
}
.sub_btn {
	background-color: #149eff;
	color: #f1f1f1;
	justify-content: center;
	align-items: center;
	border-radius: 60rpx;
	margin-right: 20rpx;
	font-size: 32rpx;
	letter-spacing: 7rpx;
	height: 50rpx;
	width: 115rpx;

}
.content {
	padding: 30rpx 20rpx 10rpx 30rpx;
	width: calc(100% - 50rpx);
	flex-direction: column;
	height: calc(100% - 70rpx - 150rpx - 55rpx);
	overflow: auto;
	.textarea {
		width: 100%;
		flex-shrink: 0;
		min-height: 300rpx;
		overflow: hidden;
		word-break: break-all;
		textarea {
			width: 100%;
		}
	}
	.filearea {
		width: 100%;
		align-items: center;
		flex-wrap: wrap;
		.file_item {
			position: relative;
			flex-shrink: 0;
			width: 30%;
			height: 220rpx;
			margin: 10rpx calc((100% - 98.4%));
			color: #007aff;
			align-items: center;
			justify-content: center;
			background: #c0c0c0;
			rotation: 0.3;
			border-radius: 30rpx;
		}
	}
}
image,
video {
	width: 225rpx;
	height: 220rpx;
	border-radius: 30rpx;
}
.file_claer {
	position: absolute;
	top: 10rpx;
	right: 10rpx;
	color: red;
}

.video-bofang {
	position: absolute;
	top: 45rpx;
	right: 70rpx;
	font-size: 80rpx;
	color: white;
}
.video_preview_info {
	display: inline-block;
	position: absolute;
	width: 150rpx;
	top: 125rpx;
	right: 35rpx;
	font-size: 30rpx;
	text-align: center;
	color: white;
}
.bottom_flxed {
	box-shadow: -1px -1px 5px #c0c0c0;
	position: fixed;
	height: 150rpx;
	width: 100%;
	flex-shrink: 0;
	bottom: 0;
	left: 0;
	background-color: white;
}
.bottom_item {
	flex-shrink: 0;
	width: 25%;
	height: 150rpx;
	color: #007aff;
	flex-direction: column;
	align-items: center;
	.bottom_item_text {
		font-size: 35rpx;
	}
}
.bottom_item_icon {
	font-size: 60rpx;
	margin-top: 10rpx;
}
.bottom_item_icon2 {
	font-size: 50rpx;
	// margin-top: 10rpx;
}
</style>
